package edu.cueb.wmis.config.security;//package edu.cueb.wmis.config.security;

//import com.lzz.server.config.security.component.CustomFilter;
//import com.lzz.server.config.security.component.CustomUrlDecisionManager;
//import com.lzz.server.pojo.Admin;
//import com.lzz.server.service.IAdminService;
//import com.lzz.server.service.IRoleService;
//import edu.cueb.wmis.config.security.component.CustomFilter;
//import edu.cueb.wmis.config.security.component.CustomUrlDecisionManager;
import edu.cueb.wmis.pojo.Admin;
import edu.cueb.wmis.service.IAdminService;
import edu.cueb.wmis.service.IRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.ObjectPostProcessor;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.access.intercept.FilterSecurityInterceptor;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.cors.CorsUtils;

/**
 * SpringSecurity配置类
 *
 * @author zhoubin
 * @since 1.0.0
 */

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

	@Autowired
	private IAdminService adminService;
	@Autowired
	private RestfulAccessDeniedHandler restfulAccessDeniedHandler;
	@Autowired
	private RestAuthenticationEntryPoint restAuthenticationEntryPoint;
	@Autowired
	private IRoleService roleService;
//	@Autowired
//	private CustomFilter customFilter;
//	@Autowired
//	private CustomUrlDecisionManager customUrlDecisionManager;

	@Override //配置，使得security走我们自己编写的userDetailService，而不用默认的。
	protected void configure(AuthenticationManagerBuilder auth) throws Exception {
		auth.userDetailsService(userDetailsService()).passwordEncoder(passwordEncoder());
	}

	/**
	 * 放行一些路径，不走拦截链
	 * @param web
	 * @throws Exception
	 */
	@Override
	public void configure(WebSecurity web) throws Exception {
		web.ignoring().antMatchers(
				"/websocket/**",
				"/**.html",
				"/login",
				"/logout/**",
				"/css/**",
				"/index.html",
				"favicon.ico",
				"/doc.html",
				"/webjars/**",
				"/swagger-resources/**",
				"/v2/api-docs/**",
				"/captcha",
				"/swagger-ui.html"

		);
	}

	@Override
	protected void configure(HttpSecurity http) throws Exception {
		//使用JWT，不需要CSRF
		http.cors().and().csrf().disable();
		http.authorizeRequests()
				.requestMatchers(CorsUtils::isPreFlightRequest).permitAll()
				.and()
				//基于jwt，不需要session
				.sessionManagement()
				.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
				.and()
				.authorizeRequests()
				//放行登录及登出
				.antMatchers("/login", "/logout").permitAll()
				.anyRequest().authenticated()
//				.withObjectPostProcessor(new ObjectPostProcessor<FilterSecurityInterceptor>() {
//					@Override
//					public <O extends FilterSecurityInterceptor> O postProcess(O object) {
//						object.setSecurityMetadataSource(customFilter);
//						object.setAccessDecisionManager(customUrlDecisionManager);
//						return object;
//					}
//				})
				.and().formLogin()
				.loginPage("/login")
				//定义登录时，用户名的 key，默认为 username
				.usernameParameter("username")
				//定义登录时，用户密码的 key，默认为 password
				.passwordParameter("password")
				.permitAll()
				.and()
				//禁用缓存
				.headers()
				.cacheControl();
		//JWT登录拦截器
		http.addFilterBefore(jwtAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class);
		//自定义异常返回结果
		http.exceptionHandling()
				.accessDeniedHandler(restfulAccessDeniedHandler)
				.authenticationEntryPoint(restAuthenticationEntryPoint);

	}


	@Override
	@Bean //相当于是重写了UserDetailsService以及里边的LoadUserByUsername的方法
	public UserDetailsService userDetailsService() {
		return username -> {
			Admin admin = adminService.getAdminByUserName(username);
			if (null != admin) {
				admin.setRoles(adminService.getRoles(admin.getId()));
				return admin;
			}
			//throw new UsernameNotFoundException("用户名或密码不正确");   //测试修改 ， 应恢复
			return null;
		};
	}


	@Bean
	public PasswordEncoder passwordEncoder() {
		return new BCryptPasswordEncoder();
	}


	@Bean
	public JwtAuthenticationFilter jwtAuthenticationFilter() {
		return new JwtAuthenticationFilter();
	}

	@Bean
	public AntPathMatcher antPathMatcher(){return new AntPathMatcher();}
}
